<template>
  <div class="homepage-module">
    <div class="filter" :style="bg">
      <div class="main">
        <div class="logintitle">宠物爱好者社区登录</div>

        <el-form ref="form" :model="form" size="normal" :rules="rules">
          <el-form-item prop="username" v-if="loginByPhone === false">
            <el-input
              prefix-icon="el-icon-user-solid"
              v-model="form.username"
              placeholder="请输入账号"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password" v-if="loginByPhone === false">
            <el-input
              prefix-icon="el-icon-lock"
              v-model="form.password"
              show-password
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item prop="username" v-if="loginByPhone === true">
            <el-input
              prefix-icon="el-icon-user-solid"
              v-model="form.phone"
              placeholder="请输入手机号"
            ></el-input>
          </el-form-item>
          <el-form-item prop="code" v-if="loginByPhone === true">
            <div style="display: flex">
              <el-input
                prefix-icon="el-icon-lock"
                v-model="form.code"
                style="width: 60%"
                placeholder="请输入短信验证码"
              ></el-input>
              <div style="width: 5%; height: 100%"></div>
              <el-button
                :disabled="countDown > 0"
                style="width: 35%"
                @click="sendVerificationCode"
                >{{
                  countDown > 0 ? `${countDown} s后重新发送` : "发送验证码"
                }}</el-button
              >
            </div>
          </el-form-item>
          <el-form-item>
            <div style="display: flex">
              <el-input
                prefix-icon="el-icon-key"
                v-model="form.validCode"
                style="width: 50%"
                placeholder="请输入图形验证码"
              ></el-input>
              <ValidCode @input="createValidCode" />
            </div>
          </el-form-item>
          <el-form-item>
            <el-button style="width: 100%" type="primary" @click="login"
              >登 录</el-button
            >
          </el-form-item>
          <el-form-item
            ><el-button type="text" @click="$router.push('/register')"
              >前往注册 >>
            </el-button>
            <el-button
              v-if="loginByPhone === false"
              type="text"
              @click="loginByPhone = true"
              >手机号登陆 >>
            </el-button>
            <el-button
              v-if="loginByPhone === true"
              type="text"
              @click="loginByPhone = false"
              >用户名登陆 >>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";
import ValidCode from "@/components/ValidCode";
import { activeRouter, activeUserRouter } from "@/utils/permission";

export default {
  name: "Login",
  components: {
    ValidCode,
  },
  data() {
    return {
      form: { username: "hwj", password: "123456", phone: "15805998773" },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      validCode: "",
      // 加背景图片,注意下加载图片的语法
      //使用assets下面的资源，在js中使用的话，路径要经过webpack中的file-loader编译，路径不能直接写
      bg: {
        backgroundImage: "url(" + require("@/assets/bg.jpg") + ")",
        backgroundRepeat: "no-repeat",
        backgroundSize: "cover",
      },
      loginByPhone: false,
      countDown: 0,
      timer: null,
    };
  },
  mounted() {
    //清除sessionStorage中的user
    sessionStorage.removeItem("user");
  },
  beforeUnmount() {
    // 组件销毁时清除定时器，避免内存泄漏
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    //短信验证码倒计时
    sendVerificationCode() {
      // 发送验证码的逻辑
      request.get("/sms?phone=" + this.form.phone).then((res) => {
        if (res.code === 0) {
          this.$message({
            type: "success",
            message: res.msg,
          });
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
      // 发送验证码后启动倒计时
      this.countDown = 60;
      this.timer = setInterval(() => {
        if (this.countDown > 0) {
          this.countDown--;
        } else {
          clearInterval(this.timer);
          this.timer = null;
        }
      }, 1000);
    },
    // 接收验证码组件提交的 4位验证码
    createValidCode(data) {
      this.validCode = data;
    },
    login() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (!this.form.validCode) {
            this.$message.error("请填写验证码");
            return;
          }
          if (
            this.form.validCode.toLowerCase() !== this.validCode.toLowerCase()
          ) {
            this.$message.error("验证码错误");
            return;
          }
          if (this.loginByPhone === false) {
            request.post("/userinfo/login", this.form).then((res) => {
              if (res.code === 0) {
                this.$message({
                  type: "success",
                  message: "登录成功",
                });
                sessionStorage.setItem("user", JSON.stringify(res.data)); // 缓存用户信息
                request
                  .get("/userRole/" + res.data.roleId)
                  .then((res) => {
                    if (res.code === 0) {
                      if (
                        res.data.roleName.includes("admin") ||
                        res.data.roleName.includes("Admin")
                      ) {
                        // 登录成功的时候更新当前路由
                        //登录成功之后进行页面的跳转，跳转到主页

                        activeRouter();
                        this.$router.push("/");
                      } else {
                        activeUserRouter();
                        this.$router.push("/user");
                      }
                    }
                  })
                  .catch((err) => {
                    console.log("axios error: " + err);
                  });
              } else {
                this.$message({
                  type: "error",
                  message: res.msg,
                });
              }
            });
          } else {  request.post("/sms/login", this.form).then((res) => {
              if (res.code === 0) {
                this.$message({
                  type: "success",
                  message: res.msg,
                });
                sessionStorage.setItem("user", JSON.stringify(res.data)); // 缓存用户信息
                request
                  .get("/userRole/" + res.data.roleId)
                  .then((res) => {
                    if (res.code === 0) {
                      if (
                        res.data.roleName.includes("admin") ||
                        res.data.roleName.includes("Admin")
                      ) {
                        // 登录成功的时候更新当前路由
                        //登录成功之后进行页面的跳转，跳转到主页

                        activeRouter();
                        this.$router.push("/");
                      } else {
                        activeUserRouter();
                        this.$router.push("/user");
                      }
                    }
                  })
                  .catch((err) => {
                    console.log("axios error: " + err);
                  });
              } else {
                this.$message({
                  type: "error",
                  message: res.msg,
                });
              }
            });
          }
        }
      });
    },
  },
};
</script>

<style scoped>
.homepage-module .homepage-module .poster img {
  z-index: 0;
  position: absolute;
}

.homepage-module .filter {
  z-index: 1;
  position: absolute;
  width: 100%;
  height: 100%;
}

.fillWidth {
  width: 100%;
}

.main {
  width: 400px;
  margin: 100px auto;
}
.logintitle {
  font-size: 30px;
  text-align: center;
  padding: 30px 0;
  color: #666;
}
</style>
